<template>
  <el-scrollbar class="scrollbar" max-height="400px">
    <reviewItemVue v-for="(item, index) in list" :key="index" :item="item"></reviewItemVue>
  </el-scrollbar>

  <div class="search-container">
    <el-form class="search-form" :model="reviewParam" label-width="90px">
      <el-form-item label="图书编号">
        <el-input style="width: 200px;" v-model="reviewParam.book_id" placeholder="请输入图书编号" />
      </el-form-item>
      <el-form-item label="评分">
        <el-rate v-model="reviewParam.rating" show-score text-color="#ff9900" score-template="{value}" />
      </el-form-item>
      <el-form-item label="评论内容">
        <el-input style="width: 400px;" v-model="reviewParam.content" type="textarea" placeholder="请输入评论内容" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" plain @click="sureReviewBook()">发表</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang='ts'>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElNotification } from 'element-plus'
import reviewItemVue from '@/components/reviewItem.vue';
import { reviewBook, getReviewBookList } from '@/request/api'

onMounted(() => {
  getList()
  userId.value = sessionStorage.getItem('user_id')
})

const list = reactive<any[]>([])
const userId = ref(sessionStorage.getItem('user_id'))
const getList = () => {
  getReviewBookList().then(async (res: any) => {
    console.log(res);
    if (res.code !== 200) {
      ElNotification({
        title: res.msg,
        type: 'error',
        duration: 1000
      })
    } else {
      list.splice(0, list.length)
      res.data.map((item: any) => list.push(item))
      // 移动到底部
      nextTick(() => {

      })

    }
  })
}

const reviewParam = reactive({
  book_id: undefined,
  user_id: userId.value,
  rating: undefined,
  content: ''
})


// 发表评论
const sureReviewBook = () => {
  reviewParam.user_id = userId.value
  reviewBook(reviewParam).then((res: any) => {
    console.log(res);
    if (res.code === 200) {
      ElNotification({
        title: res.msg,
        type: 'success',
        duration: 1000
      })
      getList()
      reviewParam.book_id = undefined
      reviewParam.rating = undefined
      reviewParam.content = ''

    }
    else {
      ElNotification({
        title: res.msg,
        type: 'error',
        duration: 1000
      })
    }
  })
}

</script>

<style scoped>
.scrollbar {
  max-height: 400px;
  padding: 10px;
  margin-bottom: 30px;
  background-color: rgb(246, 245, 245);
  border-radius: 20px;
  box-shadow: 0 8px 12px rgba(0, 0, 0, 0.2);
}

.search-container {
  border-top: 3px solid rgb(245, 245, 245);
  padding-top: 20px;
}
</style>